package com.zjgsu.demo.controller;

import com.zjgsu.demo.Repository.DeviceRepository;

import com.zjgsu.demo.nodeEntity.Device;
import com.zjgsu.demo.result.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;



@RestController
@RequestMapping("/rest/v1.0/database/device")
public class DeviceController {
    @Autowired
    DeviceRepository deviceRepository;
    //获取title实体
    @GetMapping("/get")
    public Device getDeviceByTitle(@RequestParam(value = "title") String title){
        System.out.println(title);
        Device device = deviceRepository.findDeviceByTitle(title);
        System.out.println(device);
        return device;
    }
    //存储实体
    @PostMapping("/save")
    public ResponseResult createDevice(@RequestBody Device device) throws Exception{

        Device result = deviceRepository.save(device);
        if(result!=null){
            return new ResponseResult(200,result.getTitle()+"节点创建成功！");
        }
        return new ResponseResult(500, device.getTitle()+"节点创建失败！");
    }
    //获取全部实体
    @PostMapping("/all")
    public Iterable<Device> all() throws Exception{
        Iterable<Device> devices = deviceRepository.findAll();
        return devices;
    }
    //模糊匹配title
    @GetMapping("/getR")
    public Iterable<Device> getDevicesByTitle(@RequestParam(value = "title") String title) throws Exception{
        Iterable<Device> devices = deviceRepository.findDevicesByTitle(title);
        return devices;
    }
    //为两个Dev实体设置has关系
    @GetMapping("/setRelationHas")
    public ResponseResult setRelation(@RequestParam String deviceTitle1,@RequestParam String deviceTitle2) throws Exception{
          deviceRepository.setDeviceRelation(deviceTitle1,deviceTitle2);
        return new ResponseResult(200, deviceTitle1+"和"+deviceTitle2+"拥有关系"+"创建成功");
    }
    //delete title实体
    @PostMapping("/del")
    public ResponseResult deleteDeviceByTitle(@RequestParam(value = "title") String title){
         Device device = deviceRepository.findDeviceByTitle(title);
         if(!device.getTitle().equals(null)){
             deviceRepository.deleteDeviceByTitle(device.getTitle());
             return new ResponseResult(200, device.getTitle()+"节点删除成功！");
         }else {
             return new ResponseResult(500, device.getTitle()+"节点删除失败！");
         }

    }

}
